package com.sufen.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sufen.seckill.exception.GlobalException;
import com.sufen.seckill.mapper.UserMapper;
import com.sufen.seckill.pojo.User;
import com.sufen.seckill.service.IUserService;
import com.sufen.seckill.utils.CookieUtil;
import com.sufen.seckill.utils.MD5UTIL;
import com.sufen.seckill.utils.UUIDUtil;
import com.sufen.seckill.vo.LoginVo;
import com.sufen.seckill.vo.RespBean;
import com.sufen.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2021-10-18
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile=loginVo.getMobile();
        String password=loginVo.getPassword();

        //根据手机号从数据库拿到对象
        User user=userMapper.selectById(mobile);
        //判断对象是否为空
        if(user==null){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR_NULLUSER);
        }
        //判断密码是否正确
        if(!MD5UTIL.fromPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        String ticket= UUIDUtil.uuid();
        redisTemplate.opsForValue().set("user:" + ticket,user);
//        request.getSession().setAttribute(ticket,user);
        CookieUtil.setCookie(request,response,"userTicket",ticket);
        log.info("登录成功，给浏览器传“userTicket”：Cookie值（即UUID）的键值对+往redis里存Cookie值(即UUID)：user对象的键值对都ok。此时传给前端200,前端应转到商品跳转页");
        return RespBean.success(ticket);
    }

    @Override
    public User getUserByCookie(String userTicket,HttpServletRequest request,HttpServletResponse response) {
        User user = (User)redisTemplate.opsForValue().get("user:" + userTicket);
        CookieUtil.setCookie(request,response,"userTicket",userTicket);
        return user;
    }



    /**
     * 更新密码业务：1.去mysql里面更新密码2.删除redis缓存
     * 1通过传进来的id和password，2通过传进来的userTicket
     * 目的：删除redis里旧的user信息，防止数据不一致。（如：redis里user的密码跟mysql里就不一样了。
     * @param userTicket
     * @param password
     * @return
     */
    @Override
    public RespBean updatePassword(String userTicket, String password,HttpServletRequest request,HttpServletResponse response) {
        User user=getUserByCookie(userTicket,request,response);
        if(user==null){
            throw new GlobalException(RespBeanEnum.User_NULL_ERROR);
        }
        user.setPassword(MD5UTIL.inputPassToDBPass(password,"1a2b3c4d"));
        int result=userMapper.updateById(user);
        if(result==1){
            redisTemplate.delete("user:"+userTicket);
            return RespBean.success();
        }
        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_ERROR);
    }
}
